#pragma once

#include <iostream>
#include <string>
#include <memory>
#include "Socket.hpp"
#include "Log.hpp"
#include"Connection.hpp"
using namespace ns_log;
using namespace sock_ns;

class Listenner
{
public:
    Listenner(uint16_t port) :_port(port),_listensockfd(std::make_unique<Tcp_socket>())
    {
        _listensockfd->BuildListenSocket(_port);
    }
    int Listenfd()
    {
        return _listensockfd->SockFd();
    }
    void Accepter(Connection* con)
    {
        errno = 0;
        while(true)
        {
            InetAddr addr;
            int status_code = 0;
            int sockfd = _listensockfd->AcceptSocket(&addr,&status_code);
            if(sockfd > 0)
            {
                con->_R->AddConnection(sockfd,EPOLLIN | EPOLLET,addr,NORMALSOCKET);
                LOG(INFO,"get a new link\n");
            }
            else
            {
                if(status_code == EINTR)
                {
                    continue;
                }
                else if(status_code == EWOULDBLOCK)
                {
                    LOG(INFO,"连接获取完毕!\n");
                    break;
                }
                else 
                {
                    LOG(ERROR,"获取连接失败!\n");
                    break;
                }
            }
        }
    }
    ~Listenner() {}
private:
    //监听套接字
    std::unique_ptr<Socket> _listensockfd;
    //端口号
    uint16_t _port;
};